<?php
/**
* Suggest gear is the class that offers the data in a formatted way
*
* <p>Suggest gear gets incoming text from the client machine and the
* system searches for a matching pattern against the database for any
* related entries. If any related entry that starts with the incoming
* text is found, the data is packed into the format the client machine
* can use at the browser</p>
*
* PHP version 5
*
* @category  Formatter
* @package   Suggest
* @author    Sakthivel Ganesan <sg@capjo.com>
* @author    Sasikumar Periyasamy <sasi@capjo.com>
* @copyright 2011 Capjo Systems
* @license   http://codecanyon.net/wiki/support/legal-terms/licensing-terms/ code canyon license
* @version   SVN: <1.0>
* @link      http://www.capjo.com
*/


/**
* The suggest gear is the business service layer of the application
*
* PHP version 5
*
* @category  Formatter
* @package   Suggest
* @author    Sakthivel Ganesan <sg@capjo.com>
* @author    Sasikumar Periyasamy <sasi@capjo.com>
* @copyright 2011 Capjo Systems
* @license   http://codecanyon.net/wiki/support/legal-terms/licensing-terms/ code canyon license
* @version   SVN: Release: <1.0>
* @link      http://www.capjo.com
*/

class SuggestGear
{
    /** **********************************************************************
     * Database server constants. Create a database with your preferred
     * name and alter the parameters given below to match your database
     * servers configuration
     * ***********************************************************************
     */
    public static $DBSERVER='localhost';
    // MySQL database servers IP or hostname
    public static $DBUSER='solma967_usuario';
    // MySQL username to connect to the database
    public static $DBPASSWORD='p3nt1um4';
    // MySQL password that is used to login
    public static $DBNAME='solma967_bd';
    // MySQL database
    public static $TABLENAME='anuncios';
    // MySQL table which contains the data to be searched
    public static $COLUMNNAME='titulo';
    // Column name of your table that contains the required data

    /** **********************************************************************
     * Given below are the parameters that could be used to alter the
     * theme of the suggestion box.
     * @var $AUTOSUGGESTBOXCOLOR Contains the background color of the
     *      suggestion box. Ex: If your websites background is black in
     *      color, Make this parameter as #222222.(A shade that is close
     *      to black but is not totally black) The parameter should
     *      be in Hexadecimal format.
     * @var $AUTOSUGGESTTEXTCOLOR is used to configure the text color
     *      of the suggestions. In the example stated above the font
     *      color could possibly be a lighter shade than the background
     *      color. Ex: #555555;
     * ***********************************************************************
     */
    public static $AUTOSUGGESTBOXCOLOR='#f8f8f8';
    // Background color for the auto suggestion box
    public static $AUTOSUGGESTTEXTCOLOR='#000000';
    // Text color associated with the suggestion box

    /**
     *
     * Fine tune the appearance of the suggestion box by configuring the
     * border colors individually
     */
    public static $SUGBOXLEFTBORDER="#c0d3fc";
    public static $SUGBOXTOPBORDER="#c0d3fc";
    public static $SUGBOXRIGHTBORDER="#a6bff4";
    public static $SUGBOXBOTTOMBORDER="#a6bff4";
    public static $FOOTERBACKCOLOR='#e4e4e4';
    // db associated with the application

    /**
     *
     * @var bool $FOOTERVISIBLE Set this to true to see footer
     *           at the end of the suggestion. By default
     *           escape key press would close the suggestion
     *           or the user may click anywhere in the document apart
     *           from suggestion box
     */
    public static $FOOTERVISIBLE=true;
    public static $NEEDFOOTERCOUNT=true;
    // Shows the number of displayed results to total matching results
    public static $NEEDTURNOFFSWITCH=true;
    // Configuration that permits the user to choose auto suggestion or not

    /**
     * Regular expression patterns to validate application data
     * NEED NOT ALTER AFTER THIS LINE
     * NEED NOT ALTER AFTER THIS LINE
     * NEED NOT ALTER AFTER THIS LINE
     */
    // The pattern of incoming text from the client machine
    public static $SEARCHTEXTPATTERN="/^[A-Za-z0-9 ]*$/";

    // The xml tag start to preformat the suggestion box text
    // to the client request
    public static $XMLDOC = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
        <keyword>";

    // The left angled bracket of a xml tag
    public static $XMLTAGSTART = "<";
    // The right angled bracket of a xml tag
    public static $XMLTAGEND = ">";
    // The supporting tag that holds the suggested word
    // temporarily
    public static $WORDCOL="keyword";
    // HTML bold tag
    public static $BOLDTAGSTART="<b>";
    // HTML bold tag end
    public static $BOLDTAGEND="</b>";
    // XML closing tag prefix
    public static $XMLCLOSETAG = "</";
    // The supporting tag that holds the number of suggested
    // values that matches the search pattern
    public static $COUNT = "count";
    // The support tag that holds the suggested word value
    public static $WORD="keyword";
    // Table end tag
    public static $TABLE_CLOSE_TAG="</table>";
    
    /** **********************************************************************
     * The TBL* tags contains the skeleton for the data to populated. All the
     * following values are made as canonical structure in building the html
     * table that would be published to the client machine.
     * ***********************************************************************
     */
    public static $TBLROW1="<tr style=\"height:18px;cursor:default;\">
        <td style=\"padding-left:1px;\" align=\"left\" onclick=\"xFb31z2('";
    public static $TBLROW7="<tr style=\"height:18px;cursor:default;\">
        <td style=\"padding-left:2px;
        border-bottom:1px solid #e4e4e4;\" align=\"left\" onclick=\"xFb31z2('";
    public static $TBLROW2="');\" onmouseover=\"g4A2x3c('";
    public static $TBLROW3= ";\" onmouseout=\"fQ673xtV('";
    public static $TBLROW4= ";\" id='";
    public static $TBLROW5="'>";
    public static $TBLROW6="</td></tr>";
    // End of table tow tags

    // Closing parenthesis parameter
    public static $CLOSESTRINGPARAN="')";
    // Closing string quotes to help in building tags
    public static $CLOSESTRINGQUOTES="','";
    // Count tag parameter
    public static $COUNTSTARTTAG="<count>";
    // Count tag parameter end tag
    public static $COUNTCLOSETAG="</count>";
    // Left angled bracket
    public static $ANGBRACSTART="<";
    // Right angled bracket
    public static $ANGBRACEND=">";
    // Close tag prefix
    public static $ANGBRACCLOSESTART="</";
    // Closing feature that could be used based on
    // the boolean variable configuration $FOOTERVISIBLE
    public static $FOOTERTEMPLATE="";
    public static $FOOTERTEMPLATE1="<table
        cellspacing='0' cellpadding='0' width=\"100%\">
        <tr style=\"background-color:";
    public static $FOOTERTEMPLATE3=";\">";
    public static $FOOTERRESULT="<td width='50%' align='left'
        style=\"color:#3d3d3d;
        font-family:'Lucida Grande',arial,sans-serif;
        font-size:12px; padding:3px;\">FeTChED&nbsp;de&nbsp;ToTaLR&nbsp;Resultado</td>";
    public static $FOOTERCONTROL="<td 
        title='Desativar as sugest&otilde;es.'
        width='50%' align='right'
        style=\"color:#0000ff;cursor:pointer;
        font-family:'Lucida Grande',arial,sans-serif;
        font-size:12px;\" onclick=\"sWO()\">Desligar&nbsp;</td>";
    public static $FOOTERTEMPLATE2="</tr></table>";
    
    // An empty string that could be used to
    // initialize variables
    public static $EMPTY_STR="";

    /**
     * The constructor for the SuggestGear class
     *
     */
    public function __construct()
    {
        mysql_connect(
            SuggestGear::$DBSERVER,
            SuggestGear::$DBUSER, SuggestGear::$DBPASSWORD
        );
        mysql_select_db(SuggestGear::$DBNAME);
    }

    /**
     * The function get the incoming text as a parameter and searches the
     * database for any entry. If any entry is found the system gets the
     * related entries and format it and send the formatted text to the client
     * browser
     *
     * @param string $searchText Incoming form data that has to be validated
     *
     * @return string The formatted text that the client browser can understand
     */
    public function getRelatedKeywords($searchText)
    {
        $incomingText='';
        $incomingText=str_replace("'", "''", $searchText);
        $wordcount=0;
        $incomingText=urldecode($incomingText);
        // Returns an empty string if the incoming text is
        // empty. This is to ensure that unnecessary usage
        // of resources is avoided.
        if ($incomingText=='') {
            return '';
        }
        // The system searches against a pattern to validate
        // Regular expression is used here to avoid SQL
        // injections and only the permissible values are
        // allowed after this statement
        if (!preg_match(SuggestGear::$SEARCHTEXTPATTERN, $incomingText)) {
            return '';
        }
        // The bold tag is used to highlight the remaining letters of the
        // suggestion value with bold faces
        $searchTextwithB=$searchText."<b>";
        $BEnd="</b>";
        $CustomKeyword="";
        // $sql is the query used search the table for suggestions
        $sql="select ".SuggestGear::$COLUMNNAME." from ".SuggestGear::$TABLENAME.
            " where ".SuggestGear::$COLUMNNAME." like '$incomingText%' limit 10";
        $wordresult = mysql_query($sql);
        $xmlDocument='';
        if ($wordresult) {
            $resultcount = mysql_num_rows($wordresult);
            if ($resultcount) {
                // Initialize the xmldoc used as preformatter
                $xmlDocument=SuggestGear::$XMLDOC;
                while ($row = mysql_fetch_assoc($wordresult)) {
                    $wordcount=$wordcount+1;
                    $CurrentSuggestion = $row[SuggestGear::$COLUMNNAME];
                    $CustomKeyword = $CurrentSuggestion.$BEnd;
                    // Bold faces are added to ensure
                    // the text is highlighted in suggestions
                    $CustomKeyword = preg_replace(
                        "/".$searchText."/",
                        $searchTextwithB, $CustomKeyword, 1
                    );
                    $xmlDocument = $xmlDocument.SuggestGear::$XMLTAGSTART.
                            $wordcount.SuggestGear::$XMLTAGEND;
                    $xmlDocument = $xmlDocument.$CustomKeyword;
                    $xmlDocument = $xmlDocument.SuggestGear::$XMLCLOSETAG.
                            $wordcount.SuggestGear::$XMLTAGEND;
                }
            }
            // Closing of the xml tags
            $xmlDocument = $xmlDocument.SuggestGear::$XMLTAGSTART.
                    SuggestGear::$COUNT.SuggestGear::$XMLTAGEND;
            $xmlDocument = $xmlDocument.$wordcount;
            $xmlDocument = $xmlDocument.SuggestGear::$XMLCLOSETAG.
                    SuggestGear::$COUNT.SuggestGear::$XMLTAGEND;
            $xmlDocument = $xmlDocument.SuggestGear::$XMLCLOSETAG.
                    SuggestGear::$WORD.SuggestGear::$XMLTAGEND;
        }
        // After preformatting the text to sent for
        // processing. Here the text is coverted into
        // html tags that a browser can understand
        $returnText=$this->createFormattedText($xmlDocument,$incomingText);
        return $returnText;
    }


    /**
     * The function gets the preformatted text and maps them
     * into a HTML markup that a browser can understand
     *
     * @param string $Text Incoming form data that has to be formatted
     *
     * @return string The formatted text that the client browser can understand
     */
    public function createFormattedText($Text,$incomingText)
    {
        // A prefix to ensure that the id at the html page 
        // does not matches with already available content
        // of the HTML page
        $Prefix='';
        // Future enhancement

        // Initialize the table tag based on the configuration
        $TBL_TAG = "<table id='cXy0zp15f' class='tSuggestor'
            cellspacing='0' cellpadding='0' bgColor='"
                .SuggestGear::$AUTOSUGGESTBOXCOLOR."'
            style=\"border-top:1px solid ".SuggestGear::$SUGBOXTOPBORDER.";
            border-right:1px solid ".SuggestGear::$SUGBOXRIGHTBORDER.";
            border-left:1px solid ".SuggestGear::$SUGBOXLEFTBORDER.";
            border-bottom:1px solid ".SuggestGear::$SUGBOXBOTTOMBORDER.";visibility: visible;
            left: 0px;top: 0px;width: 232px;
            table-layout:auto;overflow:hidden;
            font-family:'Lucida Grande',arial,sans-serif;
            font-size:13px;color:"
                .SuggestGear::$AUTOSUGGESTTEXTCOLOR.";\"> ";

        $count=0; // Variable that is used to count the number of entries
        $startpos=0; // The positioning parameter used in processing
        $endpos=0; // The positioning parameter used in processing
        $startpos=strpos($Text, SuggestGear::$COUNTSTARTTAG)+7;
        $endpos=strpos($Text, SuggestGear::$COUNTCLOSETAG);
        // The count of the suggested words are received here
        $count=substr($Text, $startpos, $endpos-$startpos);
        // The actual html markup is initialized here
        $htmlTableText=$TBL_TAG;
        $openTag=SuggestGear::$EMPTY_STR;
        $curWord=SuggestGear::$EMPTY_STR;
        $UseTag=SuggestGear::$TBLROW1;
        if ($count==0) {
            // If the count is zero.
            // Just return an empty string to ensure that
            // nothing is suggested by the system
            $htmlTableText=SuggestGear::$EMPTY_STR;
        } else {

        $resultssql = "select count(".SuggestGear::$COLUMNNAME.") as countcol from ".SuggestGear::$TABLENAME.
            " where ".SuggestGear::$COLUMNNAME." like '$incomingText%'";
        $result = mysql_query($resultssql);
        $totalresults=0;
        
        if ((SuggestGear::$FOOTERVISIBLE)&&(SuggestGear::$NEEDFOOTERCOUNT)) {
            if($result)
            {
                while ($row = mysql_fetch_assoc($result))
                {
                    $totalresults = $row['countcol'];
                }
            }
        }

            for ($counter=1;$counter<=$count;$counter++) {
                // with this loop the actual contents of
                // the suggestion box is built.
                $openTag=SuggestGear::$ANGBRACSTART.$counter.
                SuggestGear::$ANGBRACEND;
                // Get the starting position of the open tag
                $startpos=strpos($Text, $openTag)+strlen($openTag);
                $endpos=strpos(
                    $Text,
                    SuggestGear::$ANGBRACCLOSESTART.$counter.
                    SuggestGear::$ANGBRACEND
                );
                // Get exactly the word to be used
                $curWord=substr($Text, $startpos, $endpos-$startpos);
                $countutil=$Prefix.($counter-1);
                $UseTag=SuggestGear::$TBLROW1;
                // Finalizing the formatted text to have
                // proper closing tags at the end of each
                // suggestion
                $htmlTableText = $htmlTableText.$UseTag.
                                $curWord.SuggestGear::$TBLROW2.
                                $countutil.SuggestGear::$CLOSESTRINGQUOTES.
                                $count.
                        SuggestGear::$CLOSESTRINGPARAN.SuggestGear::$TBLROW3.
                        $countutil.SuggestGear::$CLOSESTRINGPARAN.
                        SuggestGear::$TBLROW4.
                        $countutil.SuggestGear::$TBLROW5.$curWord.
                        SuggestGear::$TBLROW6;
            }
            if (SuggestGear::$FOOTERVISIBLE) {
                // This particular part of the code is used in
                // building the footer alone based on the configuration
                // provided above
                SuggestGear::$FOOTERTEMPLATE="";
                if ((SuggestGear::$NEEDFOOTERCOUNT)
                        &&(SuggestGear::$NEEDTURNOFFSWITCH)) {
                    SuggestGear::$FOOTERTEMPLATE.=
                    SuggestGear::$FOOTERTEMPLATE1.
                    SuggestGear::$FOOTERBACKCOLOR.
                    SuggestGear::$FOOTERTEMPLATE3.
                    SuggestGear::$FOOTERRESULT.
                    SuggestGear::$FOOTERCONTROL.SuggestGear::$FOOTERTEMPLATE2;
                } else if(SuggestGear::$NEEDFOOTERCOUNT) {
                    SuggestGear::$FOOTERTEMPLATE.=
                    SuggestGear::$FOOTERTEMPLATE1.
                    SuggestGear::$FOOTERBACKCOLOR.
                    SuggestGear::$FOOTERTEMPLATE3.
                    SuggestGear::$FOOTERRESULT.
                    SuggestGear::$FOOTERTEMPLATE2;
                } else if(SuggestGear::$NEEDTURNOFFSWITCH) {
                    SuggestGear::$FOOTERTEMPLATE.=
                    SuggestGear::$FOOTERTEMPLATE1.
                    SuggestGear::$FOOTERBACKCOLOR.
                    SuggestGear::$FOOTERTEMPLATE3.
                    SuggestGear::$FOOTERCONTROL.SuggestGear::$FOOTERTEMPLATE2;
                } else {
                    SuggestGear::$FOOTERTEMPLATE="";
                }

                if (SuggestGear::$NEEDFOOTERCOUNT) {
                $searchfor='FeTChED';
                $replacewith=$count;
                SuggestGear::$FOOTERTEMPLATE=str_replace($searchfor, $replacewith,
                        SuggestGear::$FOOTERTEMPLATE);
                $searchfor='ToTaLR';
                $replacewith=$totalresults;
                SuggestGear::$FOOTERTEMPLATE=str_replace($searchfor, $replacewith,
                        SuggestGear::$FOOTERTEMPLATE);
                }

                $htmlTableText.=SuggestGear::$FOOTERTEMPLATE;
            }
            // Finalize the html with the closing tag
            $htmlTableText=$htmlTableText.SuggestGear::$TABLE_CLOSE_TAG;
        }
        return $htmlTableText;
    }
}

?>



